﻿using Microsoft.International.Converters.PinYinConverter;
using NPinyin;

namespace Bigway.Common.Services;

public class PinyinService : IPinyinService
{
    public string GetPinyin(char c)
    {
        return ChineseChar.IsValidChar(c) ? GetSpell(c) : c.ToString();
    }

    private static string GetSpell(char c)
    {
        var pinyin = Pinyin.GetPinyin(c);

        var isChinese = ChineseChar.IsValidChar(pinyin[0]);
        if (!isChinese) return pinyin;

        var chineseChar = new ChineseChar(pinyin[0]);
        foreach (var value in chineseChar.Pinyins)
        {
            if (!string.IsNullOrEmpty(value))
                return value.Remove(value.Length - 1, 1);
        }

        return pinyin;
    }
}